const group_name = 'express'
const tags = ['api', group_name]
const Joi = require('joi')

const md5 = require('md5')
const {getReq,postReq}=require('../../utils/req')
const {
  express
} = require('../../config')
var {
  Base64
} = require('js-base64')

module.exports = [{
  method: 'GET',
  path: `/express/type`,
  config: {
    tags: tags,
    description: '快递单号识别',
    validate: {
      query: {
        logisticCode: Joi.string().required().description('快递物流单号')
      }
    }
  },
  handler: async (request, h) => {
    let {
      shipperCode,
      logisticCode
    } = request.query

    let body = {
      RequestData: JSON.stringify({
        "LogisticCode": logisticCode
      }),
      RequestType: 2002,
    }
    const res = await postReqKDN(body)
    return res
  }
}, {
  method: 'GET',
  path: `/express/detail`,
  config: {
    tags: tags,
    description: '查询快递信息(快递鸟)',
    validate: {
      query: {
        shipperCode: Joi.string().required().description('快递公司编码'),
        logisticCode: Joi.string().required().description('快递物流单号')
      }
    }
  },
  handler: async (request, h) => {
    let {
      shipperCode,
      logisticCode
    } = request.query
    let body = {
      RequestData: JSON.stringify({
        "OrderCode": "",
        "ShipperCode": shipperCode,
        "LogisticCode": logisticCode,
        'IsHandleInfo': 0
      }),
      RequestType: 1002,
    }
    const res = await postReqKDN(body)
    return res
  }
}, {
  method: 'GET',
  path: '/express100/detail',
  config: {
    tags: tags,
    description: '查询快递信息(快递100)',
    validate: {
      query: {
        com: Joi.string().required().description('快递公司拼音'),
        num: Joi.string().required().description('快递物流单号')
      }
    }
  },
  handler: async (request, h) => {
    let res=await getReq100({
      com: request.query.com,
      num: request.query.num
    })
    return res
  }
}]

async function postReqKDN({
  RequestData,
  RequestType
}) {
  let url = 'http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx'
  let body = {
    RequestData: encodeURIComponent(RequestData),
    EBusinessID: express.EBusinessID,
    RequestType: RequestType,
    DataSign: encodeURIComponent(Base64.encode(md5(RequestData + express.AppKey))),
    DataType: 2
  }
  const res = await postReq(url, body)
  return res
}
async function getReq100({
  com,
  num
}) {
  var param = JSON.stringify({
      com,
      num,
      resultv2: 0,
      from: '',
      to: ''
    }),
    key = 'lCDpJMXb8886',
    customer = 'CDF7C27F9ED8E8FD820E21DAED8C94CA'
  var params = {
    customer,
    sign: md5(param + key + customer).toUpperCase(),
    param
  }
  const res = getReq('https://poll.kuaidi100.com/poll/query.do', params)
  return res
}
